<template>
  <div class="settlement-order-table-wrap">
    <div v-if="detailData && detailData.selectCost && detailData.selectCost.length" class="order-info-top">
      <div class="cost-item-list">
        <div
          v-for="(item) in detailData.selectCost"
          :key="item.id"
          :class="{'is-selected': showCostList.includes(item.id)}"
          class="cost-item"
          @click="setSelect(item.id)">
          {{ item.name }}
        </div>
      </div>
      <el-button v-if="!isNotAddCost" type="primary" size="small" class="add-order-btn" @click="openAddCost">关联新成本</el-button>
      <el-tooltip v-else content="仅部分结算的结算单可关联新成本" placement="top">
        <el-button disabled type="primary" size="small" class="add-order-btn disabled">关联新成本</el-button>
      </el-tooltip>

      <btnGroup
        v-if="hasOrderorCost && examinId && [0,5].includes(costBelong)"
        ref="btnGroupRef"
        :list="[{label:'导出确认单', exportApi:'/admin/supplier/flyUserAttachment/export', exportName:'确认单', beforeExport: exportBeforeExport, type: 'export'}]"
        style="margin-left: 10px;"
      />
    </div>
    <div v-if="ordersAndCost.orders && ordersAndCost.orders.length" class="cost-info-table">
      <div :class="{ 'order-title' : !showMobilePage, 'order-title-mobile': showMobilePage }">
        <Title title="订单信息" />
        <!-- 审批记录里面只要有 审批中和已完成 的就都不展示 -->
        <div :style="{ 'justify-content': showMobilePage && 'flex-end' }" class="flex-center">
          <div v-if="isInvite && !isExamineing && !isExamined && !operateData.auth.includes(10)" :class="{ 'btn-box-mobile': showMobilePage }" style="margin-left: 16px;">
            <el-button type="primary" size="small" class="add-order-btn" @click="handleWrite">填写订单</el-button>
            <el-button type="primary" size="small" class="add-order-btn" @click="handleInvite">邀请他人填写</el-button>
            <el-button type="primary" size="small" class="add-order-btn" @click="refreshOrderList">刷新</el-button>
          </div>
        </div>
      </div>
      <div v-if="costBelong ===0 || costBelong===5">
        <dataDisplay :data-list="dataList" style="margin: 0 0 10px 0" />
      </div>
      <u-table
        :data="ordersAndCost.orders"
        :row-height="48"
        :height="ordersAndCost.orders.length >= 30?600:''"
        use-virtual
        beautify-table
        class="fb-table"
        header-cell-class-name="order-data-header-cell">
        <u-table-column v-for="(item) in tableInfoSetting[costBelong.toString()]" v-bind="item.props" :key="item.key" :fixed="item.type === 'operate' ? 'right' : item.props.fixed">
          <template slot-scope="scope">
            <orderTableRender :table-info="item" :table-data="scope.row" @onOperate="onOperate(scope.row)" />
          </template>
        </u-table-column>
      </u-table>
    </div>
    <div v-if="ordersAndCost.costs && ordersAndCost.costs.length">
      <Title title="成本信息" style="margin-bottom: 16px;" />
      <u-table
        :data="ordersAndCost.costs"
        :row-height="48"
        :height="ordersAndCost.costs.length >= 30?600:''"
        class="fb-table"
        use-virtual
        beautify-table
        header-cell-class-name="order-data-header-cell">
        <u-table-column label="成本编号" align="left" min-width="180">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costNum" is-can-click @handelClick="toCostDetail(scope.row.orderCostItemId)" />
          </template>
        </u-table-column>
        <u-table-column label="成本项" align="left" min-width="130">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costName" />
          </template>
        </u-table-column>
        <u-table-column label="含税成本(元)" align="right" min-width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.taxCost || scope.row.taxCost === 0">{{ scope.row.taxCost/100 | moneyFilter }}</div>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column label="供应商" align="left" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.supplierName" />
          </template>
        </u-table-column>
        <u-table-column label="说明" align="left" min-width="190">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.costDescription" />
          </template>
        </u-table-column>
        <u-table-column label="成本来源" align="left" min-width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.costBelong | costBelongFilter }}</div>
          </template>
        </u-table-column>
        <u-table-column label="成本类型" align="left" min-width="90">
          <template slot-scope="scope">
            <div>{{ scope.row.costType | costTypeFilter }}</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="审批状态" width="80">
          <template slot-scope="scope">
            <StatusText :color="['#FD8546','#31CC9C', 'FF4E5F'][scope.row.costApprovalStatus]" :text="scope.row.costApprovalStatus | costApprovalStatus" />
          </template>
        </u-table-column>
        <u-table-column label="创建时间" align="left" min-width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.createDate | format('YYYY/MM/DD HH:mm') }}</div>
          </template>
        </u-table-column>
        <u-table-column label="创建人" align="left" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.creator || '--' }}
          </template>
        </u-table-column>
        <u-table-column label="成本添加时间" align="left" min-width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.submitTime">{{ scope.row.submitTime | format('YYYY/MM/DD HH:mm') }}</div>
            <div v-else>--</div>
          </template>
        </u-table-column>
      </u-table>
    </div>
    <EmptyPlaceholder
      v-if="!ordersAndCost.costs.length && !ordersAndCost.orders.length"
      :empty-img="emptyDefaultImg"
      image-size="120px" />
    <OrderSelectDialog
      ref="SelectOrderSelectDialogRef"
      :visible.sync="showOrderSelect"
      :step-one-data="{
        selectCost: detailData.selectCost,
        costBelong: costBelong,
        supplierId: supplierId
      }"
      :settle-id="settleId"
      @refreshOrderList="refreshOrderList"
    />
    <Dialog
      ref="inviteDialogRef"
      :btn1="'确认提交'"
      :btn2="'取消'"
      :requestDept="true"
      :inviteUrl="inviteUrl"
      :isInvite="isInvite"
      summary="邀请他人填写订单"
      tip="接收人请选择订单/成本负责人，或复制邀请链接给相关人员"
      @handelOK="inviteConfirm" />
    <AddCost ref="addCostRef" :detail-data="detailData" @updateDetail="updateDetail" />
    <ViewCost ref="viewCostRef" />
  </div>
</template>
<script>
// components
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import platformIcon from '@/components/Common/platformIcon';
import orderTableRender from '../module/orderTableRender';
import Dialog from '@/components/CreateOrder/orderDetail/dialog';
import OrderSelectDialog from '@/views/supplier/components/OrderSelectDialog';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import AddCost from '@/views/supplier/components/AddCost/index.vue';
import ViewCost from './viewCost';
// api
import { deleteSettleOrder, inviteOthers } from '@/api/supplier';
// filters
import { setOrderState, costBelongFilter, costTypeFilter, costApprovalStatus } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { encryption } from '@/utils';
// img
import { format } from '@/filters/date';
import { setting } from '../module/orderTableInfo.js';
import incomeAmount from '@/assets/chargeOffDetail/incomeAmount.png';
import transactionNumber from '@/assets/chargeOffDetail/transactionNumber.png';
import supplierIcon from '@/assets/mengli/mengliorder/supplier.png';
import emptyDefaultImg from '@/assets/empty-table-data.png';
import math from '@/utils/math';

import { mapState } from 'vuex';
export default {
  name: 'SettlementOrderTable',
  components: {
    Title, btnGroup,
    EmptyPlaceholder, Dialog, OrderSelectDialog,
    platformIcon, orderTableRender, dataDisplay, AddCost, ViewCost
  },
  filters: {
    setOrderState,
    moneyFilter,
    format,
    costBelongFilter,
    costTypeFilter,
    costApprovalStatus,
    profitFilter(num) {
      const percent = Number(num) * 100;
      return percent.toFixed(2) + '%';
    }
  },
  inject: {
    getIsExamineing: { default: null },
    getIsExamined: { default: null },
    freshDetail: { default: null },
    operateData: { default: { auth: [] }}
  },
  props: {
    detailData: {
      type: Object,
      default: () => { return {}; }
    },

    /**
    0: '渠道订单',
    1: '项目订单',
    2: '商务订单',
    3: '营销授权',
    4: '电商销售',
    5: '项目渠道单'
     */
    costBelong: {
      type: Number,
      default: 0
    },
    supplierId: {
      type: Number | String,
      default: null
    },
    settleId: {
      type: Number | String,
      default: null
    },
    /**
     * 审批流程状态 0：草稿 1：审核中 2：未过审 3：已撤销 4：已完成 5：待提交
     */
    processStatus: {
      type: Number,
      default: 0
    },
    /**
     * 是否已经完成结算，已关闭或者已完成
     */
    isComplete: {
      type: Boolean,
      default: false
    },
    setIsExamineing: {
      type: Object,
      default: null
    },
    examinId: {
      type: Number | String,
      default: null
    },
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    settleSchedule: {// 结算单状态 -1全部 -2草稿中 0 待提交 6审批中 1部分结算 3已完成 4已关闭
      type: Number,
      default: null
    }
  },
  data() {
    return {
      incomeAmount, transactionNumber, supplierIcon,
      emptyDefaultImg,
      costId: 0,
      pageSize: 20,
      showCostList: [],
      showOrderSelect: false,
      costAndOrderLoading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isNotAddCost() {
      // 结算单非部分状态下，置灰该按钮
      return this.settleSchedule !== 1;
    },
    hasOrderorCost() {
      return (this.ordersAndCost.orders && this.ordersAndCost.orders.length) || (this.ordersAndCost.costs && this.ordersAndCost.costs.length);
    },
    inviteUrl() {
      const inviteCode = encryption(this.settleId);
      return `${location.origin}/#/businessPage/supplierDetail?settleId=${this.settleId}&id=${this.supplierId}&isSettle=true&isInvite=${inviteCode}`;
    },
    isInvite() {
      return !!this.stepOneData.isInvite;
    },
    isExamineing() {
      if (this.setIsExamineing) {
        return this.setIsExamineing.isExamineing;
      }
      if (this.getIsExamineing) return this.getIsExamineing();
      return false;
    },
    isExamined() {
      if (this.setIsExamineing) {
        return this.setIsExamineing.isExamined;
      }
      if (this.getIsExamined) return this.getIsExamined();
      return false;
    },
    tableInfoSetting() {
      const arr = [];
      if (this.isInvite) {
        arr.push({ key: 'submitUser', props: { label: '提交人', minWidth: '120' }});
        arr.push({ key: 'submitTime', type: 'time', format: 'YYYY/MM/DD HH:mm',
          props: { label: '订单添加时间', minWidth: '170' }});
      } else {
        arr.push({ key: 'submitTime', type: 'time', format: 'YYYY/MM/DD HH:mm',
          props: { label: '订单添加时间', minWidth: '170' }});
      }
      arr.push({
        key: 'viewCost', type: 'viewCost',
        handleClick: this.viewCost,
        typeName: '查看成本', props: { label: '成本信息', fixed: 'right', minWidth: '110' }});
      if (this.isInvite && [-1, 0, 2, 3, 5].includes(this.processStatus) && !this.isExamineing && !this.isExamined && !this.operateData.auth.includes(10)) {
        arr.push({ key: 'delete', type: 'operate', typeName: '删除', props: { label: '操作' }});
      }
      const temp = _.cloneDeep(setting);
      temp[this.costBelong.toString()] = [...temp[this.costBelong.toString()], ...arr];
      let insertIndex;
      if (this.costBelong.toString() === '0') {
        insertIndex = 6;
      } else if (this.costBelong.toString() === '5') {
        insertIndex = 5;
      }
      if (temp[this.costBelong.toString()].length) {
        temp[this.costBelong.toString()].splice(insertIndex || 1, 0, { key: 'grossProfit', type: 'price', props: { label: '毛利(元)', minWidth: '100', align: 'right' }});
      }
      return temp;
    },
    ordersAndCost() {
      const showCostList = this.showCostList;
      let orders = [];
      let costs = [];
      if (this.detailData.selectCost.length === 0) return { orders, costs };
      this.detailData.selectCost.forEach(i => {
        if (showCostList.includes(i.id) && i.costList) {
          i.costList.map(it => {
            it.id ? orders = orders.concat(it) : costs = costs.concat(it);
          });
        }
      });
      return { orders, costs };
    },
    dataList() {
      const { orders } = this.ordersAndCost;
      let taxAmountTotal = null;
      let orderCostTotal = null;
      let grossProfitTotal = null;
      let profit = null;
      _.uniqBy(orders, 'orderId').forEach(i => {
        if (i.taxAmount || i.taxAmount === 0) {
          if (taxAmountTotal === null) taxAmountTotal = 0;
          taxAmountTotal = math.add(taxAmountTotal, i.taxAmount);
        }
        if (i.orderCost || i.taxAmount === 0) {
          if (orderCostTotal === null) orderCostTotal = 0;
          orderCostTotal = math.add(orderCostTotal, i.orderCost);
        }
        if (i.grossProfit || i.grossProfit === 0) {
          if (grossProfitTotal === null) grossProfitTotal = 0;
          grossProfitTotal = math.add(grossProfitTotal, i.grossProfit);
        }
      });
      if (taxAmountTotal) taxAmountTotal = math.divide(taxAmountTotal, 100);
      if (orderCostTotal) orderCostTotal = math.divide(orderCostTotal, 100);
      if (grossProfitTotal) grossProfitTotal = math.divide(grossProfitTotal, 100);
      if (taxAmountTotal) { // taxAmountTotal不能为0
        // 毛利率 = (含税金额 - 总成本) / 含税金额
        profit = math.divide(math.subtract(taxAmountTotal, orderCostTotal), taxAmountTotal);
        profit = math.multiply(profit, 100).toFixed(2);
      }
      return [
        { label: '含税金额', icon: incomeAmount, data: taxAmountTotal },
        { label: '总成本', icon: transactionNumber, data: orderCostTotal },
        { label: '总毛利', icon: supplierIcon, data: grossProfitTotal },
        { label: '毛利率', icon: supplierIcon, data: profit, unit: '%' }
      ];
    }
  },
  watch: {
    'detailData.selectCost': {
      handler(newVal) {
        if (newVal) {
          let defaultCostId = null;
          newVal.forEach(i => {
            if (!defaultCostId && i.costList && i.costList.length) {
              defaultCostId = i.id;
            }
          });
          this.costId = (defaultCostId || newVal[0].id) + '';
        }
      },
      immediate: true
    }
  },
  mounted() {
    if (this.detailData.selectCost) {
      this.showCostList = this.detailData.selectCost.map(i => i.id);
    }
  },
  methods: {
    setSelect(id) {
      if (this.showCostList.includes(id)) {
        this.showCostList = this.showCostList.filter(i => i !== id);
      } else {
        this.showCostList.push(id);
      }
    },
    viewCost(row) {
      this.$refs.viewCostRef && this.$refs.viewCostRef.openDialog(row, this.detailData);
    },
    onOperate(row) {
      this.$confirm('是否确定删除该订单/成本', '', {
        iconClass: 'del-icon',
        customClass: 'del-message del-message-cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning'
      }).then(() => {
        const params = {
          settleId: this.settleId,
          orderCostItemId: row.orderCostItemId
        };
        deleteSettleOrder(params).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.refreshOrderList();
          }
        });
      }).catch(() => {
        return false;
      });
    },
    toDetail(item) {
      if (!item.orderNum) return;
      let routeUrl = null;
      routeUrl = this.$router.resolve({
        name: 'orderDetail',
        params: { orderId: item.orderNum }
      });
      if (routeUrl) window.open(routeUrl.href, '_blank');
    },
    /**
     * 协作请款
     */

    handleWrite() {
      if (this.$refs.SelectOrderSelectDialogRef) this.$refs.SelectOrderSelectDialogRef.openDrawer();
    },
    handleInvite() {
      this.$refs.inviteDialogRef.showDialog({ defaultMsg: '有新结算单需要您协作完成' });
    },

    refreshOrderList() {
      if (this.freshDetail) this.freshDetail();
    },
    toCostDetail(id) {
      const routeUrl = this.$router.resolve({
        name: 'costDetail',
        params: { id }
      });
      window.open(routeUrl.href, '_blank');
    },
    inviteConfirm(data) {
      data.settleId = this.settleId;
      inviteOthers(data).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
        }
      }).catch(err => console.error(err.message));
    },
    exportBeforeExport() {
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport({ withdrawId: this.examinId });
      }
    },
    openAddCost() {
      this.$refs.addCostRef && this.$refs.addCostRef.openDrawer();
    },
    updateDetail() {
      this.$emit('updateDetail');
    }
  }
};
</script>
<style lang="scss" scoped>
.settlement-order-table-wrap {
  .order-info-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  & ::v-deep {
    .order-data-header-cell:first-child {
      .cell {
        padding-left: 10px;
      }
    }
    .el-table__row {
      td:first-child {
        .cell {
          padding-left: 10px;
        }
      }
    }
    .el-tabs--border-card {
      box-shadow: none;
      border: none;
      &>.el-tabs__content {
        padding: 0;
      }
    }
    .el-table::before {
      border: none;
      height: 0;
    }
    .el-select__tags {
      // overflow: hidden;
      // height: 100%;
      display: flex;
      align-items: center;
      max-width: 100%!important;
    }
    .el-tag.el-tag--info {
      color: #406EFF;
      background-color: #EFF3FB;
    }
    .el-tabs--border-card>.el-tabs__header {
      background: #fff;
      border-bottom: none;
      margin-bottom: 12px;
      // max-width: calc(100% - 136px);
      // margin-left: 136px;
      // padding: 0 32px;

    }
    .el-tabs__item {
      border: 1px solid #FAFAFC;
      background: #FAFAFC;
      margin-right: 16px;
      border-radius: 4px;
      font-size:14px;
      font-weight:400;
      color:#406EFF !important;
      height: 30px;
      line-height: 30px;
      padding: 0 8px !important;
    }
    .el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active {
      border-color: #406EFF !important;
      background: #E6EDFF;
      &.is-focus {
        box-shadow: none;
      }
    }
    .el-tabs__nav {
      padding: 1px;
    }
    .el-tabs__nav-prev, .el-tabs__nav-next {
      width: 24px;
      &:hover {
        color: #406EFF;
      }
    }
    .el-tabs__nav-prev {
      display: flex;
      height: 31px;
      align-items: center;
    }
    .el-tabs__nav-next {
      right: -10px;
      height: 31px;
      display: flex;
      align-items: center;
    }
  }
  .order-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    &::v-deep {
      .title-head {
        flex: unset;
      }
    }
  }
  .order-title-mobile {
    margin-bottom: 12px;
    .btn-box-mobile {
      margin-left: 0 !important;
      margin-top: 16px;
      display: flex;
      flex-flow: row wrap;
    }
  }
  .add-order-btn {
    background-color: #fff;
    color: #406EFF;
    border-color: #406EFF;
    &.disabled {
      opacity: 0.4;
    }
  }
  .cost-info-table {
    margin-bottom: 32px;
  }
  .cost-item-list {
    display: flex;
    flex: 1;
    flex-wrap: wrap;
    .cost-item {
      border: 1px solid #FAFAFC;
      background: #FAFAFC;
      margin-right: 16px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
      color:#406EFF;
      height: 28px;
      line-height: 28px;
      padding: 0 12px;
      cursor: pointer;
      white-space: nowrap;
      margin-bottom: 12px;
      &.is-selected {
        border-color: #406EFF;
        background: #E6EDFF;
      }
    }
  }
}

</style>
